<?php

class CodeVersion extends Base {

    protected function init() {
        parent::init();

        $this->attributes['id'] = 0;
        $this->attributes['uid'] = 0;
        $this->attributes['name'] = '';
        $this->attributes['url'] = '';
        $this->attributes['content'] = '';
        $this->attributes['created'] = time();
        $this->attributes['updated'] = time();
    }

    public function __construct($id = null) {
        $this->init();

        if (!empty($id)) {
            if ($id instanceof stdClass) { // is a DB row
                if (!$this->load($id->id)) {
                    throw new Exception("[CodeVersion] Fail to load id by db row");
                }
            } else if($id instanceof CodeVersion) {
                foreach ($id->attributes as $key => $value) {
                    $this->attributes[$key] = $value;
                }
            } else if (is_string($id)) { // if it is a version name
                $id = get_code_version_by_name($id);
                if ($id) {
                    foreach ($id->attributes as $key => $value) {
                        $this->attributes[$key] = $value;
                    }
                }
            } else if (is_numeric($id)){
                if (!$this->load($id)) {
                    throw new Exception("[CodeVersion] Fail to load id for given id: ".$id);
                }
            } else { // other, exception
                throw new Exception("[CodeVersion] Invalid parameter exception: Unrecognised Value.");
            }
        }
    }

    /**
     * @param $id
     * @return bool
     */
    protected function load($id) {
        $row = get_code_version_as_row($id);

        $obj_array = (array) $row;

        foreach ($obj_array as $key => $value) {
            $this->attributes[$key] = $value;
        }

        return true;
    }

    /**
     * Get version content
     * @return mixed
     */
    public function getCode() {
        return $this->get("content");
    }

    public function save() {
        error_log("Save version code to DB.");
        return create_version(
            $this->get('id'),
            $this->get('uid'),
            $this->get('name'),
            $this->get('url'),
            $this->get('content'),
            $this->get('created'),
            $this->get('updated')
        );
    }
}

/**
 * @param $id
 * @return object
 */
function get_code_version_as_row($id) {
    $id = (int) $id;
    return get_data_row("SELECT * from versions where id={$id}");
}

/**
 * @param $name
 * @param User $user
 * @return object
 */
function get_code_version_by_name($name, $user=NULL) {
    if (!$user) {
        $user = get_loggedin_user();
    }
    if ($user) {
        $uid = $user->get("id");
        $name = mysql_real_escape_string($name);
        return get_data_row("SELECT * FROM versions v WHERE v.uid={$uid} AND name={$name}");
    }
    return false;
}

/**
 * Create or update code version
 * @param $id
 * @param $uid
 * @param $name
 * @param $url
 * @param $content
 * @param $created
 * @param $updated
 * @return bool|int
 * @throws Exception
 */
function create_version($id, $uid, $name, $url, $content, $created, $updated) {
    $id = (int) $id;
    $uid = (int) $uid;
    if (!$uid) {
        $uid = (int)get_loggedin_userid();
    }
    $name = mysql_real_escape_string($name);
    $url = mysql_real_escape_string($url);
    $content = mysql_real_escape_string($content);
    $created = (int) $created;
    $updated = (int) $updated;

    $row = null;
    if ($id) {
        $row = get_code_version_as_row($id);
    }
    if ($row) {
        // TODO: update the version
        error_log('----------------->Update CodeVersion: '.$id);
    } else {
        // insert new version
        $query = "INSERT INTO `versions` (`uid`, `name`, `url`, `content`, `created`, `updated`) VALUES ($uid, '$name', '$url', '$content', $created, $updated)";
        $id = insert_data($query);

    }

    return $id;
}

/**
 * Get user's code versions
 * @param int $uid
 * @return array
 */
function get_user_versions($uid = 0) {
    if (!$uid) {
        $uid = get_loggedin_userid();
    }

    $uid = (int)$uid;

    $query = "SELECT * FROM versions WHERE uid={$uid}";
    $rows = get_data($query);

    $versions = array();
    foreach ($rows as $row) {
        $versions[] = new CodeVersion($row);
    }

    return $versions;
}